package com.captain.special.二叉树.中等;

import com.captain.leetcode.TreeNode;

import java.util.*;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/5/15 18:00
 */
public class 二叉树的锯齿形层序遍历103 {
    List<List<Integer>> ans = new ArrayList<>();
    Queue<TreeNode> queue = new ArrayDeque<>();
    boolean isLeft = true;

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (root == null) return new ArrayList<>();
        queue.add(root);
        sequence(root);
        return ans;
    }

    public void sequence(TreeNode node) {
        while (!queue.isEmpty()) {
            int size = queue.size();
            LinkedList<Integer> level = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                if (isLeft) {
                    level.addLast(cur.val);
                } else {
                    level.addFirst(cur.val);
                }
                if (cur.left != null) {
                    queue.add(cur.left);
                }
                if (cur.right != null) {
                    queue.add(cur.right);
                }
            }
            isLeft = !isLeft;
            ans.add(level);
        }
    }
}
